package com.aloda.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.aloda.constant.ErrorCode;
import com.aloda.context.UserBaseContext;
import com.aloda.dto.user.UserSafetyDTO;
import com.aloda.entity.UserToken;
import com.aloda.exception.BaseException;
import com.aloda.result.Result;
import com.aloda.service.UserTokenService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 客户端token controller
 */
@Slf4j
@RestController("token-user")
@RequestMapping("/user/token")
public class UserTokenController {

    @Resource
    private UserTokenService userTokenService;

    /**
     * 通过用户id查询token余量
     *
     * @return
     */
    @GetMapping
    public Result<Long> getTokenNumsByUserId() {
        Long id = UserBaseContext.getUser().getId();
        if (id == null) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        LambdaQueryWrapper<UserToken> userTokenLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userTokenLambdaQueryWrapper.eq(UserToken::getUserId, id);
        UserToken userToken = userTokenService.getOne(userTokenLambdaQueryWrapper);
        if (BeanUtil.isEmpty(userToken)) {
            return Result.success(0L);
        }
        return Result.success(userToken.getTokenNum());
    }

    /**
     * 赠送新用户tokens
     *
     * @return
     */
    @PostMapping
    public Result<Boolean> giveNewUserTokens() {
        Long id = UserBaseContext.getUser().getId();
        log.info("赠送新用户{}tokens", id);
        return Result.success(userTokenService.giveNewUserTokens());
    }

    /**
     * 判断用户有没有tokens记录
     * @return
     */
    @GetMapping("/judge")
    public Result<Boolean> judgeUserToken() {
        UserSafetyDTO user = UserBaseContext.getUser();
        if (BeanUtil.isEmpty(user)) {
            return Result.success(Boolean.TRUE);
        }
        LambdaQueryWrapper<UserToken> userTokenLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userTokenLambdaQueryWrapper.eq(UserToken::getUserId, user.getId());
        UserToken userToken = userTokenService.getOne(userTokenLambdaQueryWrapper);
        return Result.success(BeanUtil.isEmpty(userToken));
    }
}
